package com.ruoyi.agentAdd.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.mapper.SysAgentMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.agentAdd.domain.SysAgentAdd;
import com.ruoyi.agentAdd.service.ISysAgentAddService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 代理商充值订单Controller
 *
 * @author ruoyi
 * @date 2024-06-21
 */
@RestController
@RequestMapping("/agentAdd/agentAdd")
public class SysAgentAddController extends BaseController
{
    @Autowired
    private ISysAgentAddService sysAgentAddService;

    @Autowired
    private SysAgentMapper agentMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 查询代理商充值订单列表
     */
    @PreAuthorize("@ss.hasPermi('agentAdd:agentAdd:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysAgentAdd sysAgentAdd, @RequestParam(name = "params[beginCreateTime]", required = false) Date beginCreateTime,
                              @RequestParam(name = "params[endCreateTime]", required = false) Date endCreateTime)
    {

        Long deptId = SecurityUtils.getDeptId();

        String type = deptMapper.selectDeptById(deptId).getType();
        List<SysAgentAdd> list=null;
        if (beginCreateTime!=null) {
            sysAgentAdd.setBeginCreateTime(beginCreateTime);
        }

        if (endCreateTime!=null) {
            sysAgentAdd.setEndCreateTime(endCreateTime);
        }


        if (type.equals("0")) {
            //管理员
            startPage();
            list = sysAgentAddService.selectSysAgentAddList(sysAgentAdd);

        }
        else if (type.equals("1")) {
            //代理商
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("用户信息异常");
            }
            sysAgentAdd.setAgentId(agents.get(0).getId());

            //管理员
            startPage();
            list = sysAgentAddService.selectSysAgentAddList(sysAgentAdd);

        }
        else {
            throw new ServiceException("您没有权限操作");
        }


        sysAgentAdd.setDeptId(SecurityUtils.getDeptId());

        if (beginCreateTime!=null) {
            sysAgentAdd.setBeginCreateTime(beginCreateTime);
        }

        if (endCreateTime!=null) {
            sysAgentAdd.setEndCreateTime(endCreateTime);
        }



        if (CollectionUtils.isEmpty(list)) {
            return getDataTable(list);
        }
        List<Long> agentIds = new ArrayList<>(list.stream().map(SysAgentAdd::getAgentId).collect(Collectors.toSet()));
        List<SysAgent> agents = agentMapper.selectSysAgentByIds(agentIds);
        Map<Long, String> agentMap = agents.stream().collect(Collectors.toMap(SysAgent::getId, c -> c.getName()));

        //封装操作人
        List<Long> userIds = new ArrayList<>(list.stream().map(SysAgentAdd::getUserId).collect(Collectors.toSet()));
        Map<Long, String> userMap = userMapper.selectByIds(userIds).stream().collect(Collectors.toMap(SysUser::getUserId, c -> c.getUserName()));


        for (SysAgentAdd agentAdd : list) {
            agentAdd.setAgentName(agentMap.get(agentAdd.getAgentId()));
            agentAdd.setUserName(userMap.get(agentAdd.getUserId()));
        }



        return getDataTable(list);
    }

    /**
     * 导出代理商充值订单列表
     */
    @PreAuthorize("@ss.hasPermi('agentAdd:agentAdd:export')")
    @Log(title = "代理商充值订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,SysAgentAdd sysAgentAdd, @RequestParam(name = "params[beginCreateTime]", required = false) Date beginCreateTime,
                       @RequestParam(name = "params[endCreateTime]", required = false) Date endCreateTime)
    {

        if (SecurityUtils.getDeptId()!=100l) {
            throw  new ServiceException("该用户没有权限");
        }
        sysAgentAdd.setDeptId(SecurityUtils.getDeptId());

        if (beginCreateTime!=null) {
            sysAgentAdd.setBeginCreateTime(beginCreateTime);
        }

        if (endCreateTime!=null) {
            sysAgentAdd.setEndCreateTime(endCreateTime);
        }


        startPage();
        List<SysAgentAdd> list = sysAgentAddService.selectSysAgentAddList(sysAgentAdd);

        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("数据为空");
        }
        List<Long> agentIds = new ArrayList<>(list.stream().map(SysAgentAdd::getAgentId).collect(Collectors.toSet()));
        List<SysAgent> agents = agentMapper.selectSysAgentByIds(agentIds);
        Map<Long, String> agentMap = agents.stream().collect(Collectors.toMap(SysAgent::getId, c -> c.getName()));

        //封装操作人
        List<Long> userIds = new ArrayList<>(list.stream().map(SysAgentAdd::getUserId).collect(Collectors.toSet()));
        Map<Long, String> userMap = userMapper.selectByIds(userIds).stream().collect(Collectors.toMap(SysUser::getUserId, c -> c.getUserName()));


        for (SysAgentAdd agentAdd : list) {
            agentAdd.setAgentName(agentMap.get(agentAdd.getAgentId()));
            agentAdd.setUserName(userMap.get(agentAdd.getUserId()));
        }

        ExcelUtil<SysAgentAdd> util = new ExcelUtil<SysAgentAdd>(SysAgentAdd.class);
        util.exportExcel(response, list, "代理商充值订单数据");
    }

    /**
     * 获取代理商充值订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('agentAdd:agentAdd:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysAgentAddService.selectSysAgentAddById(id));
    }

    /**
     * 新增代理商充值订单
     */
    @PreAuthorize("@ss.hasPermi('agentAdd:agentAdd:add')")
    @Log(title = "代理商充值订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysAgentAdd sysAgentAdd)
    {
        return toAjax(sysAgentAddService.insertSysAgentAdd(sysAgentAdd));
    }

    /**
     * 修改代理商充值订单
     */
    @PreAuthorize("@ss.hasPermi('agentAdd:agentAdd:edit')")
    @Log(title = "代理商充值订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysAgentAdd sysAgentAdd)
    {
        return toAjax(sysAgentAddService.updateSysAgentAdd(sysAgentAdd));
    }

    /**
     * 删除代理商充值订单
     */
    @PreAuthorize("@ss.hasPermi('agentAdd:agentAdd:remove')")
    @Log(title = "代理商充值订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysAgentAddService.deleteSysAgentAddByIds(ids));
    }
}
